import java.util.*;

/**
 * @Author @fiber-cloud
 * @Date 2025/8/3 16:18
 * 二叉树模块
 */
public class Test {



    static class TreeNode{
        public char val;
        public TreeNode left;//存储左孩子的引用
        public TreeNode right;//存储右孩子的引用

        public TreeNode(char val){
            this.val = val;
        }
    }



    //构建一个二叉树 前序遍历为：A B D E H C F G
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        //TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        //E.right = H;

        return A;
        /**
         *         A
         *        / \
         *      B    C
         *    / \   / \
         *   D  E  F   G
         *       \
         *        H
         */
    }

    //从一个特殊格式的字符串按先序遍历顺序构建二叉树
    private static int i = 0;
    public static TreeNode createTree(String str) {
        TreeNode root = null;
        if (str.charAt(i) != '#'){
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        }else {
            i++;
        }
        return root;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if (root == null){
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);

    }
    //前序遍历——用List实现
    static List<Character> list1 = new ArrayList<>();
    public  List<Character> preorderTraversal(TreeNode root) {

        if (root == null){
            return list1;
        }
        System.out.print(root.val + " ");
        list1.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list1;
    }
    public List<Character> preorderTraversal2(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        System.out.print(root.val+" ");
        ret.add(root.val);
        List<Character> leftTree = preorderTraversal2(root.left);
        List<Character> rightTree = preorderTraversal2(root.right);
        return ret;
    }


    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null){
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }
    //后续遍历
    public  void postOrder(TreeNode root){
        if (root == null){
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }
    //非递归的前中后序遍历
    //前序遍历
    public static void preOrder1(TreeNode root) {
        //这里用栈实现
        if (root == null){
            return;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode t = stack.pop();
            System.out.print(t.val +" ");
            // 右子先入栈（后出），左子后入栈（先出）
            if (t.right != null){
                stack.push(t.right);
            }
            if (t.left != null){
                stack.push(t.left);
            }
        }
    }

    //中序遍历
    public void inOrder2(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode t = root;

        while (t != null || !stack.isEmpty()){
            //找到最左边节点
            while (t != null){
                stack.push(t);
                t = t.left;
            }

            t = stack.pop();
            System.out.print(t.val + " ");
            t =  t.right;
        }
    }
    //后续遍历——双栈实现
    public  void postOrder2(TreeNode root){
        if (root == null){
            return;
        }
        Stack<TreeNode> s1 = new Stack<>();
        Stack<TreeNode> s2 = new Stack<>();
        s1.push(root);

        while (!s1.isEmpty()){
            TreeNode t = s1.pop();//pop()移除并返回栈顶元素
            s2.push(t);

            if (t.left != null){
                s1.push(t.left);//push()压入栈顶
            }

            if (t.right != null){
                s1.push(t.right);
            }
        }

        while (!s2.isEmpty()){
            System.out.print(s2.pop().val + " ");
        }
    }


    // 获取树中节点的个数
    public static int nodeSize = 0;
    public int size(TreeNode root) {
        if (root == null){
            return 0;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
        return nodeSize;
    }

    // 获取叶子节点的个数
    public int getLeafNodeCount(TreeNode root) {
        //当root的左右子树都为null时，说明root为叶子节点
        if (root == null){
            return 0;
        }
        if (root.left == null && root.right == null){
            return 1;
        }
        int count = getLeafNodeCount(root.left)+getLeafNodeCount(root.right);
        return count;
    }

    // 获取第K层节点的个数
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null || k <= 0){
            return 0;
        }
        if (k == 1){
            return 1;
        }
        int count = getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
        return count;
    }

    // 获取二叉树的高度
    public int getHeight(TreeNode root) {
        if (root == null){
            return 0;
        }
        //看每个结点的最大层次
        int l = getHeight(root.left);
        int r = getHeight(root.right);
        return l > r ? l+1 : r+1;
    }

    // 检测值为value的元素是否存在
    public TreeNode find(TreeNode root, int val) {
        if (root == null){
            return null;
        }
        if (root.val == val){
            return root;
        }
        TreeNode t1 = find(root.left,val);
        if (t1 != null){
            return t1;
        }
        TreeNode t2 = find(root.right,val);
        if (t2 != null){
            return t2;
        }
        return null;
    }
    //层序遍历——用队列实现
    public void levelOrder(TreeNode root) {
        if (root == null){
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//放入队列
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();//看一下队头是谁,并移除队头
            System.out.print(cur.val + " ");
            if (cur.left != null){
                queue.offer(cur.left);
            }
            if (cur.right != null){
                queue.offer(cur.right);
            }
        }
    }
    // 判断一棵树是不是完全二叉树
    public boolean isCompleteTree(TreeNode root) {
        if (root == null){
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            TreeNode cur = queue.poll();

            if (cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        //判断队列剩下的值 是否有 非null的数据
        while (!queue.isEmpty()){
            TreeNode pop = queue.poll();
            if (pop != null){
                return false;
            }
        }
        return true;
    }

    //找相同的树
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if ((p == null && q != null) || (p != null && q == null)){
            return false;
        }
        if (p == null && q == null){
            return true;
        }
        if (p.val != q.val){
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }


    //另一颗树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null){
            return false;
        }
        if (isSameTree(root,subRoot)){
            return true;
        }
        if (isSubtree(root.left,subRoot)){
            return true;
        }
        if (isSubtree(root.right,subRoot)){
            return true;
        }
        return false;
    }

    //二叉树的最大深度
    public int maxDepth(TreeNode root) {
        if (root == null){
            return 0;
        }
        int leftHight = maxDepth(root.left);
        int rightHight = maxDepth(root.right);
        return leftHight > rightHight ? leftHight+1 : rightHight+1;
    }

    //平衡二叉树
    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);

        return Math.abs(leftH-rightH) < 2 &&
                isBalanced(root.left) &&
                isBalanced(root.right);
    }

    //对称二叉树
    public boolean isSymmetric(TreeNode root) {
        if (root == null){
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }

    private boolean isSymmetricChild(TreeNode left, TreeNode right) {
        if (left == null && right == null){
            return true;
        }
        if(left == null && right != null ||
                left != null && right == null ) {
            return false;
        }
        if (left.val != right.val){
            return false;
        }
        return isSymmetricChild(left.left,right.right) &&
                isSymmetricChild(left.right,right.left);
    }
}
